/*
 * $URL: https://dnsprobe.googlecode.com/svn/trunk/dnsprobe/src/dnsprobe/gui/listener/FrontGuiActionListener.java $
 * 
 * Copyright (c) 2009, Anonymous
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Anonymous nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY ANONYMOUS ''AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL ANONYMOUS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */

package dnsprobe.gui.listener;


import static dnsprobe.Constants.COMMAND_CHANGE_CUSTOM_NAMESERVER;
import static dnsprobe.Constants.COMMAND_CHANGE_NAMESERVER;
import static dnsprobe.Constants.COMMAND_LOAD_HOSTLIST;
import static dnsprobe.Constants.COMMAND_SAVE_EXPORT;
import static dnsprobe.Constants.COMMAND_START_RESOLVE;
import static dnsprobe.Constants.COMMAND_STOP_RESOLVE;
import static dnsprobe.Constants.EXPORT_FILENAME;
import static dnsprobe.Constants.GUI_MSG_EXPORT_FAIL;
import static dnsprobe.Constants.GUI_MSG_EXPORT_NODATA;
import static dnsprobe.Constants.GUI_MSG_EXPORT_SUCCESS;
import static dnsprobe.Constants.GUI_MSG_RESOLV_UNKNOWN_HOST;
import static dnsprobe.Constants.GUI_MSG_IMPORT_LOADED;
import static dnsprobe.Constants.PROVIDER_CUSTOM;
import static dnsprobe.Constants.GUI_LABEL_EXPORT_CHOICE_ALL;
import static dnsprobe.Constants.GUI_LABEL_EXPORT_CHOICE_DIFF;
import static dnsprobe.Constants.GUI_LABEL_EXPORT_CHOICE_EQUAL;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import dnsprobe.Application;
import dnsprobe.ApplicationData;
import dnsprobe.FileHandler;
import dnsprobe.gui.FrontGui;
import dnsprobe.gui.UpdateThread;
import dnsprobe.net.domain.Hostname;
import dnsprobe.net.nameserver.AccessProvider;

/**
 * ActionListener fuer die GUI
 * 
 * @author BerndBernhardson
 * @author anon004
 * @author snoop
 * @version $Id: FrontGuiActionListener.java 138 2009-07-02 09:57:02Z anonymousRepo@hellokitty.com $
 *
 */
public class FrontGuiActionListener implements ActionListener
{
	/**
	 * Referenz auf Das ApplicationData Objekt
	 */
	private final ApplicationData applicationData;
	
	/**
	 * Referenz auf das GUI-Objekt
	 */
	private final FrontGui frontGui;
	
	/**
	 * Konstruktor
	 * 
	 * @param frontGui Die frontGui Instanz auf die der Listener wirken soll
	 */
	public FrontGuiActionListener(final FrontGui frontGui)
	{
		this.applicationData = Application.getData();
		this.frontGui        = frontGui;
	}
	
	/**
	 * Dispatcher fuer die Aktionen
	 */
	@Override
	public void actionPerformed(final ActionEvent e) 
	{
		// lookup starten
		if(COMMAND_START_RESOLVE.equals(e.getActionCommand()))
		{
			startResolver();
			
			UpdateThread ut = new UpdateThread();
			ut.setFrontGui(frontGui);
			Thread t = new Thread(ut);
			t.start();
		}
		
		// lookup anhalten
		if(COMMAND_STOP_RESOLVE.equals(e.getActionCommand()))
		{
			stopResolver();
		}
		
		// host-datei laden
		if(COMMAND_LOAD_HOSTLIST.equals(e.getActionCommand()))
		{
			loadHostList();
		}
		
		// ergebnis exportieren
		if(COMMAND_SAVE_EXPORT.equals(e.getActionCommand()))
		{
			saveExport();
		}
		
		// nameserver aktualisieren
		if(COMMAND_CHANGE_NAMESERVER.equals(e.getActionCommand()))
		{
			changeNameserver();
		}
		
		// own dns aendern
		if(COMMAND_CHANGE_CUSTOM_NAMESERVER.equals(e.getActionCommand()))
		{
			changeCustomNameserver();
		}
	}
	
	/**
	 * Startet den Resolver
	 */
	private void startResolver()
	{
		try
		{
			Application.getResolverThread().startResolver();
		}
		catch(UnknownHostException e)
		{
			frontGui.printLog(GUI_MSG_RESOLV_UNKNOWN_HOST);
		}
	}

	/**
	 * Stoppt den Resolver
	 */
	private void stopResolver()
	{
		Application.getResolverThread().stopResolver();
	}

	/**
	 * Laedt eine neue Host-Datei
	 */
	private void loadHostList()
	{
		final File file;
		
		file = frontGui.chooseInputFile();
		
		if(file == null)
		{
			return;
		}
		
		try
		{
			final List<Hostname> newData;
			
			newData = FileHandler.readHostListFromFile(file);
			
			// alte daten verwerfen
			if(newData.size() > 0)
			{
				applicationData.getHostnameList().clear();
				applicationData.getHostnameList().addAll(newData);
				
				frontGui.setImportPath(file.getPath());
				frontGui.updateIpTableModel();
				
				Application.getResolverThread().getStatistics().reset();
				frontGui.setStatistics(Application.getResolverThread().getStatistics());
				
				frontGui.clearLog();
				frontGui.printLog(GUI_MSG_IMPORT_LOADED + file.getPath());
			}
		}
		catch(FileNotFoundException e)
		{
			// should not happen
			frontGui.printLog("Datei wurde nicht gefunden");
		}
		catch(IOException e)
		{
			frontGui.printLog("Datei konnte nicht gelesen werden");
		}
	}
	
	/**
	 * Exportiert die aktuelle Ergebnis-Liste
	 */
	private void saveExport()
	{
		if(applicationData.getHostnameList().size() == 0)
		{
			frontGui.printLog(GUI_MSG_EXPORT_NODATA);
			return;
		}
		
		final File file;
		
		file = frontGui.chooseOutputFile(new File(EXPORT_FILENAME));
		
		if(file == null)
		{
			return;
		}
		
		
		int exportType;
		
		if(frontGui.getExportType().equals(GUI_LABEL_EXPORT_CHOICE_DIFF))
		{
			exportType = FileHandler.EXPORT_DIFF;
		}
		else if(frontGui.getExportType().equals(GUI_LABEL_EXPORT_CHOICE_EQUAL))
		{
			exportType = FileHandler.EXPORT_EQUAL;
		}
		else 
		{
			exportType = FileHandler.EXPORT_ALL;
		}
		
		
		
		try
		{
			FileHandler.writeHostListToFile
			(
				file,
				applicationData.getHostnameList(), 
				applicationData.getCurrentProvider(),
				exportType
			);
		}
		catch(IOException ex)
		{
			frontGui.printLog(GUI_MSG_EXPORT_FAIL);
			return;
		}
		
		frontGui.printLog(GUI_MSG_EXPORT_SUCCESS);
	}
	
	/**
	 * Aendert den aktuellen Nameserver
	 */
	private void changeNameserver()
	{
		try
		{
			final AccessProvider accessProvider;
			
			accessProvider = frontGui.getNameserverObject();
			
			InetAddress.getByName(accessProvider.getAddress());
			
			applicationData.setCurrentProvider(accessProvider);
			frontGui.setNameserver(accessProvider.getAddress(), accessProvider.isEditable());
		}
		catch(UnknownHostException e)
		{
			frontGui.printLog(GUI_MSG_RESOLV_UNKNOWN_HOST);
		}
	}

	/**
	 * Aendert die Adresse des User-Nameservers
	 */
	private void changeCustomNameserver()
	{
		final AccessProvider accessProvider;
		
		accessProvider = frontGui.getNameserverObject();
		
		// nur der 'own dns' eintrag sollte aenderbar sein
		if(accessProvider != PROVIDER_CUSTOM)
		{
			// should not happen
			return;
		}
		
		try
		{
			final String address;
			
			address = InetAddress.getByName(frontGui.getNameserver()).getHostAddress();
			
			applicationData.getCurrentProvider().setAddress(address);
		}
		catch(UnknownHostException e)
		{
			frontGui.printLog(GUI_MSG_RESOLV_UNKNOWN_HOST);
		}
	}
}
